package com.decard.baselibrarydemo.utils;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;

/**
 * 低功耗BLE
 */
public class BleUtils {
	
	BluetoothManager mBluetoothManager;
	BluetoothAdapter mBluetoothAdapter;
	public Context mContext;
	public static final int REQUEST_OPEN_BT_CODE = 0x01;
	private static final String TAG="BleTools";
	public BleUtils(Context c){
		mContext = c;

	}


	
	
	/**
	 * 初始化BLE
	 * @return true   || false 
	 */
	public  boolean initBLE() {
		if (!mContext.getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_BLUETOOTH_LE)) {
			return false;
		}

		if (mBluetoothManager == null) {
			mBluetoothManager = (BluetoothManager) mContext
					.getSystemService(Context.BLUETOOTH_SERVICE);
		}

		if (mBluetoothManager == null) {
			return false;
		}

		if (mBluetoothAdapter == null) {
			mBluetoothAdapter = mBluetoothManager.getAdapter();
		}

		if (mBluetoothAdapter == null) {
			return false;
		}
		

		return true;
	}
	
	
	/**
	 * 蓝牙打开状态
	 * @return true || false 
	 */
	public boolean isEnabled() {

		if (mBluetoothManager == null) {
			return false;
		}
		if (mBluetoothAdapter == null) {
			return false;
		}
		return mBluetoothAdapter.isEnabled();

	}

	
	/**
	 * 打开蓝牙
	 * @return true  || false 
	 */
	public boolean enable() {

		if (mBluetoothManager == null) {
			return false;
		}
		if (mBluetoothAdapter == null) {
			return false;
		}
		return mBluetoothAdapter.enable();

	}
	
	
	
	
	public void requestEnableBluetooth() {
		Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		((Activity)mContext).startActivityForResult(intent, BleUtils.REQUEST_OPEN_BT_CODE);
	}
	
	
	/**
	 * scan ble device
	 * @return 
	 */
	public boolean scanLeDevice(BluetoothAdapter.LeScanCallback mLeScanCallback) {
		if (mBluetoothAdapter == null) {
			return false;
		}
		mBluetoothAdapter.stopLeScan(mLeScanCallback);
		return mBluetoothAdapter.startLeScan(mLeScanCallback);
	}
	
	
	/**
	 * stop scaning
	 * */
	public void stopLeDevice(BluetoothAdapter.LeScanCallback mLeScanCallback) {
		if (mBluetoothAdapter == null) {
			return;
		}
		mBluetoothAdapter.stopLeScan(mLeScanCallback);
	}
	
	
	
	
	
}
